package org.xurui.sxl.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设置免打扰时间开关
 */
@Slf4j
public class CmdCodec_CLASSSWITCH implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.CLASSSWITCH.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,CLASSSWITCH,seq,para,HHMMSS,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*TJ,7893267561,V4,CLASSSWITCH,130305,1,13036,V,2230.7021,N,11355.1445,E,0.00,2.8,271112,FFFFFFFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.CLASSSWITCH.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.CLASSSWITCH.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        String para=payloadArr[5];

        Map<String, Object> properties = new HashMap<>();
        properties.put("para",para);
        properties.put("uptime",payloadArr[6]);
        properties.put("s",payloadArr[7]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[8],"lat"));
        properties.put("d",payloadArr[9]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[10],"lon"));
        properties.put("g",payloadArr[11]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[12]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[13]));
        properties.put("upday", payloadArr[14]);
        String trackerStatusHex = payloadArr[15];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,CLASSSWITCH,HHMMSS,switch_flag#
        //例子：*TJ,7893267561,CLASSSWITCH,130305,1#
        //参数说明：switch_flag 0：关闭免打扰；1：打开常规免打扰功能；2：打开静默功能
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String switchFlag="0";
            if(paramsMap.get("switchFlag")!=null && !paramsMap.get("switchFlag").equals("")) {
                switchFlag=paramsMap.get("switchFlag").toString();
            }

            String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
            /*StringBuffer sb = new StringBuffer();
            sb.append("*");
            sb.append(zzs);//TODO 需要修改成根据设备动态加载
            sb.append(",");
            sb.append(message.getDeviceId());
            sb.append(",");
            sb.append(CommandEnum.CLASSSWITCH.name());
            sb.append(",");
            sb.append(time);
            sb.append(",");
            sb.append(switchFlag);
            sb.append("#");*/
            ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.CLASSSWITCH.name()+"_"+time,message.getMessageId(),60*3*1000);
            //return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));
            return SxlMessageUtils.SxlCmd.getInstance()
                .appendAndAddSeparator(zzs)
                .appendAndAddSeparator(message.getDeviceId())
                .appendAndAddSeparator(CommandEnum.CLASSSWITCH.name())
                .appendAndAddSeparator(time)
                .append(switchFlag).buildEncodeMessage();

        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.WIFISCAN.name(),message);
            }
            return null;
        }
    }
}
